<template>
  <div ref="container" class="infinite" :style="{height: height}">
    <div ref="inner" class="inner">
      <!-- 列表标题 -->
      <slot name="title"></slot>
      <!-- 这里放列表 -->
      <slot></slot>
      <!-- 加载中的动画 -->
      <van-loading v-if="loading" size="24px" class="loading">加载中...</van-loading>
      <!-- 加载完成的动画 -->
      <div v-if="nomore" class="loading">没有更多了</div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'InfiniteScroll',
  props: {
    height: {
      type: String,
      default: '100%'
    },
    loading: {
      type: Boolean,
      default: false
    },
    nomore: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      containerHeight: 0,
      innerHeight: 0
    }
  },
  created() {

  },
  mounted() {
    this.containerHeight = this.$refs.container.clientHeight
    this.innerHeight = this.$refs.inner.offsetHeight
    this.$refs.container.addEventListener('scroll', this.initScroll)
  },
  methods: {
    initScroll(e) {
      if (this.loading || this.nomore) return
      this.innerHeight = this.$refs.inner.offsetHeight
      const scrollTop = e.target.scrollTop
      if (scrollTop + this.containerHeight >= this.innerHeight) {
        this.$emit('loadBottom')
      }
    }
  }
}
</script>
<style lang="less" scoped>
  .infinite {
    width: 100%;
    overflow: auto;
    -webkit-overflow-scrolling: touch; // 解决iOS滚动问题
  }
  .loading{
    text-align:center;
    padding: 30px 0;
    color: #969799;
    font-size: 30px;
  }
  .inner{
    height: 100%;
  }
</style>

